

//复制
function copy_init(prefix,id) {
	//复制功能
	var clip = null;
	
	clip = new ZeroClipboard.Client();
	clip.setHandCursor( true );
	
	
	clip.addEventListener('load', function (client) {
		//alert("Flash movie loaded and ready.");
	});
	
	clip.addEventListener('mouseOver', function (client) {

        var url = $('#' + prefix + '_clip_button-' + id).html();
        re = /&amp;/g;        // 创建正则表达式模式。
        url = url.replace(re, "&");   // 交换每一对单词。
        clip.setText(url);
	});
	
	clip.addEventListener('complete', function (client, text) {
			
		var $txt = $('#' + prefix + '_clip_button-' + id);
		
		if(!$txt.hasClass('bg-green')){
			$txt.addClass('bg-green');
		}

        //60秒后删除
        setTimeout(function(){
            $('#'+clip.movieId).remove();
        },3 * 60 * 1000);
	});
	
	clip.glue( prefix + '_clip_button-' + id, prefix + '_clip_container-' + id );
}



//汇总
var $div_summary = null;

$(function(){
	
	
	//设置宽度
	var $body = $('body');
	$body.css('margin-left','3px');
	
	
	$div_summary = $('#div_summary');
	
	
	//修改后保存
	var $input = $('input[name="order_sn"],input[name="invoice_no"],input[name="goods_amount"],input[name="bonus_money"],input[name="shipping_fee"],input[name="paid_amount"],input[name="remark"]');
	
	$input.change(function(){
		
		var task_id = $('#task_id').val();
		var id		= $(this).attr('id');
		var order_id= GetPostfix(id);
		var name 	= $(this).attr('name');
		var value 	= $.trim($(this).val());		
		
		$(this).removeClass().addClass('tr w40 bg-white');
		
		var $txt = $(this);
		
		$.post('/index.php/Admin/Order/order_update',{
			'task_id'	:task_id,
			'order_id'	:order_id,
			'item'		:name,
			'value'		:value
		},function(data){
			if(data.success){
				$txt.removeClass().addClass('tr w40 bg-green');

                //更新下单ip
                if(data.data.order_ip != ''){
                    $('#order_ip-' + order_id).html(data.data.order_ip);
                }

				//更新汇总信息
				task_order_summary()

				//备注修改后
				if(name == 'remark'){
					$txt.attr('title',value);
				}
				
				if(name == 'bonus_money' || name == 'paid_amount'){
					//计算实际总金额
					calc_real_price(order_id);
				}

			}else{
				$txt.removeClass().addClass('tr w40 bg-red');
				alert(data.message);
			}
		},'JSON');
		
	});
	
	
	//全选
	var $check_all = $("#check_all");
	var $check_orders = $("input[name='check_orders']");
	
	$check_all.click(function(){
		
		var checked = false;
		if($(this).is(':checked')){
			checked = true;
		}
		
		$check_orders.each(function(i){
			var $check = $($check_orders[i]);
			
			if(checked){
				if(!$check.is(':checked')){
					$check.click();
				}
			}else{
				if($check.is(':checked')){
					$check.click();
				}
			}
		});
		
	});

	
	//设置异常订单
	var $is_exception = $('a[name="is_exception"]');
	
	$is_exception.click(function(){
		var order_id = $(this).attr('order_id');
		
		var is_exception = 0;
		if(!$(this).hasClass('color-red')){
			is_exception = 1;
		}
		//设置是否异常
		set_is_exception(order_id,is_exception);
	});
	
	
	//隐藏显示备注
    var $tr_more = $('#tr-more');
    var $class_tr_more = $('.tr-more');

    var $btnHideComment = $('#btnHideComment');
    var $btnShowComment = $('#btnShowComment');

	
	//显示

    $btnShowComment.click(function(){
        $(this).parent().hide();
        $class_tr_more.show();
        $btnHideComment.parent().show();
	});
	
	//隐藏
	$btnHideComment.click(function(){
        $(this).parent().hide();
        $class_tr_more.hide();
        $btnShowComment.parent().show();
	});

	/*
	//划入划出显示备注
	var comment_timer = null;
	var $div_comment = $('#div_comment');
	$div_comment.mouseover(function(){
		
		if(comment_timer != null){
			clearTimeout(comment_timer);
			comment_timer = null;
		}else{
			
			if(!$form_task_log.is(':visible')){
			
				comment_timer = setTimeout(function(){
					$form_task_log.show();
					clearTimeout(comment_timer);
					comment_timer = null;
				},300);
			}
			
		}

	}).mouseout(function(){
		
		if(comment_timer != null){
			clearTimeout(comment_timer);
			comment_timer = null;
		}else{
			
			if($form_task_log.is(':visible')){
				
				comment_timer = setTimeout(function(){
					$form_task_log.hide();
					clearTimeout(comment_timer);
					comment_timer = null;
				},300);
			}
			
		}
	});
	
	*/
	
	//提交备注
	var options = { 
	        beforeSubmit:  showRequest,  // pre-submit callback 
	        success:       showResponse,  // post-submit callback 
	 
	        dataType:  'json',        // 'xml', 'script', or 'json' (expected server response type) 
	        clearForm: false        // clear all form fields after successful submit 

	    }; 
	 
	    
    //提交备注
    $('#form_task_log').submit(function() { 

        $(this).ajaxSubmit(options); 

        return false; 
    });
	    
	
	//分配订单
    var $btnAssignOrder = $('#btnAssignOrder');
    $btnAssignOrder.click(function(){
    	var $checked_orders = $("input[name='check_orders']:checked");
    	var task_id = $('#task_id').val();
    	
    	if($checked_orders.length == 0){
    		alert('请先选择要分配的订单');
    		return false;
    	}
    	
    	var orders = new Array();
    	$checked_orders.each(function(i){
    		var order_id = $($checked_orders[i]).val();
    		orders.push(order_id);
    	});
    	
    	var order_admin_id = $('#order_admin_id').val();
    	    	
    	$.post('/index.php/Admin/Task/assign_order',{
    		'task_id':task_id,
    		'check_orders':orders.toString(),
    		'order_admin_id':order_admin_id
    	},function(data){
    		if(data.success){
    			alert(data.message);
    			location.reload(true);
    		}else{
    			alert(data.message);
    		}
    	},'JSON');
    	
    	
    });
    
    
    
    //分配会员
    var $btnAssignMember = $('#btnAssignMember');
    $btnAssignMember.click(function(){
    	
    	var task_id = $('#task_id').val();
    	
    	$.post('/index.php/Admin/Task/assign_member',{
    		'id':task_id
    	},function(data){
    		if(data.success){
    			alert(data.message);
    			location.reload(true);
    		}else{
    			alert(data.message);
    		}
    	},'JSON');
    });
    
    
    //分配下单URL
    var $btnAssignURL = $('#btnAssignURL');
    $btnAssignURL.click(function(){
    	
    	var task_id = $('#task_id').val();
    	
    	$.post('/index.php/Admin/Task/assign_url',{
    		'id':task_id
    	},function(data){
    		if(data.success){
    			alert(data.message);
    			location.reload(true);
    		}else{
    			alert(data.message);
    		}
    	},'JSON');
    });
    
    
    //分配会员
    var $btnAssignAddress = $('#btnAssignAddress');
    $btnAssignAddress.click(function(){
    	
    	var task_id = $('#task_id').val();
    	
    	$.post('/index.php/Admin/Task/assign_address',{
    		'id':task_id
    	},function(data){
    		if(data.success){
    			alert(data.message);
    			location.reload(true);
    		}else{
    			alert(data.message);
    		}
    	},'JSON');
    });
    
    
    
    //修改快递
    var $shipping_select = $('select[name="shippings"]');
    $shipping_select.change(function(){
    	var order_id 	= GetPostfix($(this).attr('id'));
    	var shipping_id = $(this).val();
    	
    	$.post('/index.php/Admin/Order/order_update',{
			'order_id'	:order_id,
			'item'		:'shipping_id',
			'value'		:shipping_id
		},function(data){
			if(data.success){
				//更新汇总信息
				$('#invoice_no-' + order_id).focus();
			}else{
				alert(data.message);
			}
		},'JSON');

    });
    

    //复制功能 
	var $copy_items = $('.my_clip_button');
	$copy_items.mouseover(function(){
		if((typeof $(this).attr('inited')) == 'undefined'){		
			$(this).attr('inited','1');
			
			var id = GetPostfix($(this).attr('id'));
			var prefix = $(this).attr('prefix');
			copy_init(prefix,id);
		}
	});
	
	/*//预加载，效果不佳，慢卡
	$copy_items.each(function(){
		var id = GetPostfix($(this).attr('id'));
		var prefix = $(this).attr('prefix');
		copy_init(prefix,id);
	});
	*/
    
	//范围
	var range_max = $check_orders.length;
	
    //分配选取订单
	$( "#slider-range" ).slider({
	      range: true,
	      min: 0,
	      max: range_max,
	      values: [ 0, 0 ],
	      slide: function( event, ui ) {
	        $( "#range" ).val(ui.values[ 0 ] + " - " + ui.values[ 1 ] );
	        
	        //范围选择
	        checked_orders_range($check_orders,ui.values[ 0 ],ui.values[ 1 ]);
	        
	        
	      }
	 });
	
	
	//执行完毕
	var $btnFinish = $('#btnFinish');
	$btnFinish.click(function(){
		
		var task_id = $('#task_id').val();
		
		if(!confirm('确认执行完毕?')){
			return false;
		}
		
		$.post('/index.php/Admin/Task/set_finish',
			{'task_id':task_id},
			function(data){
				if(data.success){
					alert(data.message);
				}else{
					alert(data.message);
				}
		},'JSON');
		
	});
	
	
	
	
	
	//分配订单
    var $btnResetMemberId = $('#btnResetMemberId');
    $btnResetMemberId.click(function(){

    	var $checked_orders = $("input[name='check_orders']:checked");
    	    	
    	if($checked_orders.length == 0){
    		alert('请先选择要重置的订单');
    		return false;
    	}
    	
    	if(!confirm('确认要重置分配的帐号?')){
    		return false;
    	}
    	
    	
    	var orders = new Array();
    	$checked_orders.each(function(i){
    		var order_id = $($checked_orders[i]).val();
    		orders.push(order_id);
    	});
    	
    	
    	    	
    	$.post('/index.php/Admin/Task/reset_member_id',{
    		'check_orders':orders.toString()
    	},function(data){
    		if(data.success){
    			alert(data.message);
    		}else{
    			alert(data.message);
    		}
            $btnAssignMember.click();
    	},'JSON');
    	
    });

    //收货确认
    var $btnOrderReceive  = $('#btnOrderReceive');
    $btnOrderReceive.click(function(){
        var $checked_orders = $("input[name='check_orders']:checked");
        var task_id = $('#task_id').val();
        var day_span= $('#day_span').val();

        if($checked_orders.length == 0){
            alert('请先选择要收货确认的订单');
            return false;
        }

        //与开始时间小于三天
        if(parseInt(day_span) < 3){
            if(!confirm('当前时间与任务开始时间小于3天，确认要提交订单收货确认?')){
                return false;
            }
        }

        if(!confirm('请确认提交订单收货确认?')){
            return false;
        }

        if(!confirm('请再次确认提交订单收货确认?')){
            return false;
        }

        var orders = new Array();
        $checked_orders.each(function(i){
            var order_id = $($checked_orders[i]).val();
            orders.push(order_id);
        });

        alert('收货确认操作时间较长，请耐心等待，不要关闭窗口!');

        receive_submit_orders(orders);
    });


    //批量重置收货状态到未收货
    var $btnReceiveStatusReset  = $('#btnReceiveStatusReset');
    $btnReceiveStatusReset.click(function(){
        var $checked_orders = $("input[name='check_orders']:checked");
        var task_id = $('#task_id').val();

        if($checked_orders.length == 0){
            alert('请先选择要重置为 "未收货" 的订单');
            return false;
        }

        if(!confirm('请确认重置订单为:未收货?')){
            return false;
        }

        if(!confirm('请再次确认重置订单为:未收货?')){
            return false;
        }

        var orders = new Array();
        $checked_orders.each(function(i){
            var order_id = $($checked_orders[i]).val();
            orders.push(order_id);
        });

        receive_status_reset(orders);
    });



    //重置收货状态
    var $receive_status = $('.receive_status');
    $receive_status.click(function(){

        var txt = $(this).text();
        if(txt == '收货失败' || txt == '待收货(收货中)'){
            reset_receive_status($(this));
        }
    });



    //划入显示备注
    var $aRemark = $("a[name='is_exception']");

    //留言提示
    $aRemark.cluetip({
        cluetipClass: 'jtip',
        arrows: true,
        width: '300px',
        dropShadow: false,
        sticky: true,
        mouseOutClose: true,
        closePosition: 'title',
        readFromCache:false,
        closeText: '<img src="/Img/cluetip/cross.png" alt="close" />'
    });


    //更新显示汇总
    task_order_summary();
});

function getTop(e){
	var offset = e.offsetTop;
	if(e.offsetParent != null) offset += getTop(e.offsetParent);
	return offset;
}

//更新汇总信息
function task_order_summary(){

	var task_id = $div_summary.attr('task_id');
	
	$div_summary.load('/index.php/Admin/Task/task_order_summary?id=' + task_id);	
}

//设置是否异常
function set_is_exception(order_id,is_exception){

	var $checked = $('#is_exception-' + order_id);
	
	$.post('/index.php/Admin/Order/order_update',{
		'order_id'	:order_id,
		'item'		:'is_exception',
		'value'		:is_exception
	},function(data){
		if(data.success){
			if(is_exception){
				$checked.attr('class','color-red').attr('title','异常订单');
			}else{
				$checked.attr('class','').attr('title','');
			}
			
			
			
		}else{
			alert(data.message);
		}
	},'JSON');
}

//post提交
function showRequest(formData, jqForm, options) { 
    //var queryString = $.param(formData); 
    return true; 
} 

function showResponse(data, statusText, xhr, $form)  {
	
	var form_id = $form.attr('id');

	if(data.success){
		alert(data.message);
				
		if(form_id == 'form_task_log'){
			location.reload(true);
		}
		
	}else{
		alert(data.message);
	}
}

//选择范围订单
function checked_orders_range($check_orders,start,end){
	
	$check_orders.each(function(i){

		var $check = $($check_orders[i]);
		var checked = false;
		if($(this).is(':checked')){
			checked = true;
		}
		
		var index = i + 1;
		
		if(index >= start && index <= end){
			//在范围内			
			if(!checked){
				$check.click();
			}
			
		}else{
			//不在范围内
			if(checked){
				$check.click();
			}
		}
	});
}

//计算实际总金额
function calc_real_price(id){
	
	var bonus_money = parseFloat($('#bonus_money-' + id).val());
	var paid_amount = parseFloat($('#paid_amount-' + id).val());
	
	if(isNaN(bonus_money)){
		bonus_money = 0;
	}
	if(isNaN(paid_amount)){
		paid_amount = 0;
	}
	
	var real_price = (bonus_money + paid_amount).toFixed(2);
	
	$('#real_price-' + id).html(real_price);
}


//批量收货确认订单
function batch_order_receive(orders){

    var order_id = orders.shift();

    //状态
    var $receive_status = $('#receive_status-' + order_id);

    $receive_status.html('<span style="color:blue">待收货(收货中)</span>');

    $.post('/Cli/jd_receive.php',{'order_id':order_id},function(data){

        if(data.success){

            $receive_status.html('<span style="color:green">已收货</span>');
            //取消掉
            var $check_order = $('#orders_' + order_id);
            if($check_order.is(':checked')){
                $check_order.click();
            }
        }else{
            $receive_status.html('<span style="color:red">收货失败</span>');
        }

        if(orders.length > 0){
            batch_order_receive(orders);
        }else{
            $('#btnOrderReceive').attr('disabled',false).val('7.收货确认');
            alert('收货确认已全部操作完毕!');
        }
    },'JSON');
}


//重置状态
function reset_receive_status($td){

    var id = $td.attr('id');
    var order_id= GetPostfix(id);

    $.post('/index.php/Admin/Order/order_update',{
        'order_id'	:order_id,
        'item'      :'receive_status',
        'value'     :0
    },function(data){
        if(data.success){
            $td.html('<span style="color:gray">未收货</span>');
        }else{
            alert(data.message);
        }
    },'JSON');
}


/**
 * 提交订单去收货确认
 */
function receive_submit_orders(orders){

    var check_orders = orders.toString();


    $.post('/index.php/Admin/Task/receive_submit_orders',{'check_orders':check_orders},function(data){
        if(data.success){
            alert(data.message);
            location.reload(true);
        }else{
            alert(data.message);
        }
    },'JSON');
}

/**
 * 提交订单去收货确认
 */
function receive_status_reset(orders){

    var check_orders = orders.toString();

    $.post('/index.php/Admin/Task/receive_status_reset',{'check_orders':check_orders},function(data){
        if(data.success){
            alert(data.message);
            location.reload(true);
        }else{
            alert(data.message);
        }
    },'JSON');
}


/**
 * 修改保存备注
 * @param taObj
 * @param order_id
 */
function order_remark_change(taObj,order_id){
    var remark = $.trim($(taObj).val());
    $.post('/index.php/Admin/Task/order_remark_update',{'order_id':order_id,'remark':remark},function(data){
        if(data.success){

            var $a = $('#is_exception-' + order_id);

            if(remark == ''){
                if($a.hasClass('bg-green')){
                    $a.removeClass('bg-green')
                }
            }else{
                if(!$a.hasClass('bg-green')){
                    $a.addClass('bg-green')
                }
            }

        }else{
            alert(data.message);
        }
    },'JSON');
}